<template>
    <el-drawer v-model="drawer" title="I am the title" :with-header="false">
        <h2 class="topP">{{isShowAiChartHistory===false?'AI 问答':'AI 问答聊天记录'}}</h2>
        <div class="talkArea">
            <div style="height: 100%" v-if="isShowAiChartHistory===false">
              <div class="hello" v-if="message.length===0">你好，今天能帮你什么</div>
              <div v-if="message.length!==0" class="talks">
                <div v-for="(item,index) in message"
                     :class="{'ai_area':item.belongs==='ai','user_area':item.belongs==='user'}">
                  <div>{{item.content}}</div>
                </div>
                <div class="ai_area">
                  <el-skeleton
                      style="width: 78%;display: flow-root;"
                      :rows="10"
                      v-if="message.length%2!==0"
                      animated />
                </div>
              </div>
            </div>
            <div class="talks" v-if="isShowAiChartHistory===true">
              <ai-chart-history @messageSent="handleMessage"/>
            </div>
        </div>
        <el-input
                v-model="user_talk"
                :rows="3"
                type="textarea"
                placeholder="Please input"
                @keyup.enter="askQuestion"
        />
        <div class="caozuoArea">
          <el-tooltip
              class="box-item"
              effect="dark"
              content="发送"
              placement="top-start"
          >
            <i @click="askQuestion" class="iconfont icon-fasong" id="send"></i>
          </el-tooltip>

          <el-tooltip
              class="box-item"
              effect="dark"
              content="新聊天"
              placement="top-start"
          >
            <i @click="storeCommuncationHistory" class="iconfont icon-xinliaotian" id="send" style="margin-left: 14px;"></i>
          </el-tooltip>
          <el-tooltip
              class="box-item"
              effect="dark"
              content="聊天历史"
              placement="top-start"
          >
            <i @click="openChartHistory" class="iconfont icon-lishijilu" id="send" style="margin-left: 14px;"></i>
          </el-tooltip>
        </div>
    </el-drawer>
</template>

<script setup>
import {onMounted, ref, watch} from 'vue'
import AiChartHistory from "@/components/AiCommunication/AiChartHistory/AiChartHistory.vue";
    import {useCounterStore} from "@/stores/counter.js";
    import  {ElMessage} from "element-plus";
    import axios from "axios";
    const drawer = ref(false)

    const CounterStore=useCounterStore()

    watch(()=>CounterStore.isOpenAiTalking,()=>{
        if(CounterStore.isOpenAiTalking===true){
            drawer.value=true
        }
    },{immediate:true})
    watch(drawer,()=>{
        if(drawer.value===false){
            CounterStore.isOpenAiTalking=false
        }
    })

    // 将聊天记录滑动到底部
   function slideToTheBottom() {
     if(message.value.length===0){return}
      const div=document.querySelector('.talks')
      div.scrollTop=div.scrollHeight
   }

    let message= ref([]);

    // 初始化ai聊天记录，更新message
    onMounted( async () => {
      function f() {
        message.value = CounterStore.AiChartHistory
      }
      await f()
      slideToTheBottom()
    })

    let user_talk=ref('')

    // 发送问题到后端，并更新message
    async function askQuestion() {
      if(user_talk.value===''){
        ElMessage({
          message: '请输入您的问题',
          type: 'warning'
        })
        return
      }
      slideToTheBottom()
      let user_chat=user_talk.value
      user_talk.value=''
      await message.value.push({belongs:'user',content:user_chat})
      slideToTheBottom()
      try {
        const response = await axios.post('/api/chat/ask', {question: user_chat})
        let ai_response = response.data.split('\n').map(line => line.replace(/^data:/, '').trim()).join('')
        await message.value.push({belongs:'ai',content:ai_response})
        slideToTheBottom()
      } catch (error) {
        console.error('Error during axios:', error);
      }
      CounterStore.AiChartHistory=message.value
    }

    //检查localStorage里是否有'AiChartHistory'，避免报错
    function InitChartHistory() {
      let aiChartHistory = localStorage.getItem('AiChartHistory');
      if (!aiChartHistory) {
        localStorage.setItem('AiChartHistory',JSON.stringify([]))
      }
    }
    InitChartHistory()

    // 存储聊天记录到localStorage
    function storeCommuncationHistory() {
      isShowAiChartHistory.value=false
      if(message.value.length===0){return}
      let aiChartHistory = localStorage.getItem('AiChartHistory');
      let messages=JSON.parse(aiChartHistory)
      messages.push(message.value)
      message.value=[]
      CounterStore.AiChartHistory=message.value
      localStorage.setItem('AiChartHistory',JSON.stringify(messages))
    }

    let isShowAiChartHistory=ref(false)

    // 控制历史记录区域显示与否
    function ControlHistoryArea(TureOrFalse) {
      isShowAiChartHistory.value = TureOrFalse
      CounterStore.isShowAIHostory = TureOrFalse
    }

    // 打开历史记录区域，并存储当前聊天记录
    async function openChartHistory() {
      async function f() {
        await storeCommuncationHistory()
        ControlHistoryArea(true)
      }
      await f()
      const div=document.querySelector('.talks')
      div.scrollTop=div.scrollHeight
    }

    // 处理从历史记录区域接收的消息
const handleMessage = async (receivedMessage) => {
  message.value = receivedMessage;
  await ControlHistoryArea(false);
  slideToTheBottom()
};

</script>

<style scoped>
.topP{
    margin: 0;
    padding-left: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #d0cece;
}
.talkArea{
    height: 74%;
    padding-top: 15px;
}
.hello{
    text-align: center;
    line-height: 23em;
    font-size: 23px;
    font-weight: 600;
}
.talks{
    height: 99%;
    overflow-y: auto;
    flex: 1;
}
.ai_area{
    /*background-color: #e1f5fe; !* AI消息的背景色 *!*/
    align-self: flex-start; /* 靠左 */
    word-wrap: break-word; /* 自动换行 */
    margin-bottom: 15px;
    margin-top: 15px;
}
.ai_area div{
    background-color: #e1f5fe;
    width: auto;
    display: inline-flex;
    position: relative;
    border-radius: 17px;
    padding: 6px 10px 6px 10px;
    max-width: 78%;
}
.user_area{
    display: flex;
    justify-content: right;
}
.user_area div{
    background-color: #c8e6c9;
    width: fit-content;
    position: relative;
    display: inline-flex;
    justify-content: right;
    padding: 6px 10px 6px 10px;
    border-radius: 15px;
    max-width: 80%;
    margin-right: 12px;
}
.caozuoArea{
    margin-top: 5px;
}
#send{
    cursor: pointer;
    font-size: 24px;
    color: #6b6b98;
}

</style>